package com.wowangz.cms.systemmanage.handautotask.api;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.wowangz.cms.common.pojo.AjaxDataEntity;
import com.wowangz.cms.common.utils.DataFormat;
import com.wowangz.cms.common.utils.SysConstant;
import com.wowangz.cms.component.datagrid.pojo.DataGrid;
import com.wowangz.cms.component.datagrid.pojo.DataResult;
import com.wowangz.cms.component.datagrid.pojo.DataStyle;
import com.wowangz.cms.component.datagrid.pojo.PangingParam;
import com.wowangz.cms.component.datagrid.utils.DataTypeConstant;
import com.wowangz.cms.component.datagrid.utils.PangingTools;
import com.wowangz.cms.syscore.IssTransactionContainer;
import com.wowangz.cms.syscore.api.BaseController;
import com.wowangz.cms.syscore.api.JSONFactory;
import com.wowangz.cms.syscore.autotask.pojo.Autotask;
import com.wowangz.cms.syscore.utils.MessageResourcesUtils;
import com.wowangz.cms.syscore.utils.ServletUtils;
import com.wowangz.cms.systemmanage.handautotask.service.HandAutoTaskService;

@Scope("prototype")
@Controller
public class HandAutoTaskController extends BaseController{
	@SuppressWarnings("unused")
	private static Logger logger = LoggerFactory.getLogger(HandAutoTaskController.class);
	/*************
	 * 跳转到人工数据同步   查询列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemManage/handAutoTask/toHandAutoTaskList.web",method = {RequestMethod.GET,RequestMethod.POST})
	public String toHandAutoTaskListPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/systemmanage/handautotask/handautotaskList";
	}
	/****************
	 * 人工数据同步   列表数据查询
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemManage/handAutoTask/queryHandAutoTaskListInfoDataGrid.json",method = {RequestMethod.GET,RequestMethod.POST})
	public void queryHandAutoTaskListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {
		HandAutoTaskService handAutoTaskService = (HandAutoTaskService) IssTransactionContainer.getInstance(HandAutoTaskService.class, false);
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;
		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);
			if(map.containsKey("taskcode")){
				map.put("taskcode",map.get("taskcode").toString().toUpperCase());
			}
			long resultCount = handAutoTaskService.findResultCount(map);
			List<Autotask> resultList = handAutoTaskService.findResultList(map);
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);
			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("code", DataTypeConstant.STRING);
			dataStyle.addDepict("name", DataTypeConstant.STRING);
			dataStyle.addDepict("executeclass", DataTypeConstant.STRING);
			dataStyle.addDepict("executemodel", DataTypeConstant.STRING);
			dataStyle.addDepict("description", DataTypeConstant.STRING);
			dataStyle.addDepict("servername", DataTypeConstant.STRING);
			dataStyle.addDepictByFunction("executestatus", SysConstant.ExecuteStatus.class, "getName", new Class[]{long.class});
			dataStyle.addDepictByFunction("taskstatus", SysConstant.TaskStatus.class, "getName", new Class[]{long.class});
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/************
	 * 点击  人工数据同步  同步按钮
	 * @param request
	 * @param response
	 * @param model
	 */
	@RequestMapping(value = "/systemManage/handAutoTask/synchronousHandAutoTask.json",method = {RequestMethod.GET,RequestMethod.POST})
	public void synchronousHandAutoTask(HttpServletRequest request, HttpServletResponse response, Model model) {
		AjaxDataEntity ajaxDataEntity = new AjaxDataEntity();
		try {
			HandAutoTaskService handAutoTaskService = (HandAutoTaskService) IssTransactionContainer.getInstance(HandAutoTaskService.class, false);
			String strId = request.getParameter("id");
			if(strId!=null){
				String[] ids=strId.split(",");
				for (int i = 0; i < ids.length; i++) {
					Long id=Long.valueOf(ids[i]);
					if(ids[i]!=null && !("").equals(ids[i])){
						//获得执行的自动任务
						Autotask sysautotask=handAutoTaskService.queryHandAutoTaskByID(id);
						if(sysautotask!=null){
							startNewJob(sysautotask);
						}
					}
				}
			}
			userContext.setInfoMessage(MessageResourcesUtils.getMessage(request, "systemmanage.headautotask.list.alert2"));
			response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
		} catch (Exception e) {
			e.printStackTrace();
			userContext.setErrorMessage(e.getMessage());
			try {
				response.getWriter().write(JSONFactory.toJSONString(ajaxDataEntity, userContext));
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
	}
	/*************
	 * 跳转到 自动任务执行结构   查询列表页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/systemManage/autoTaskResult/toAutoTaskResultList.web",method = {RequestMethod.GET,RequestMethod.POST})
	public String toAutoTaskResultListPage(HttpServletRequest request, HttpServletResponse response, Model model) {
		return "/WEB-INF/jsp/systemmanage/handautotask/autotaskresultList";
	}
	/****************
	 *  自动任务执行结构   列表数据查询
	 * @param request
	 * @param response
	 * @param model
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping(value = "/systemManage/autoTaskResult/queryAutoTaskResultListInfoDataGrid.json",method = {RequestMethod.GET,RequestMethod.POST})
	public void queryAutoTaskResultListInfoDataGrid(HttpServletRequest request, HttpServletResponse response, Model model) {
		HandAutoTaskService handAutoTaskService = (HandAutoTaskService) IssTransactionContainer.getInstance(HandAutoTaskService.class, false);
		PangingParam pangingParam = null;
		DataResult dataResult = new DataResult();
		DataGrid dataGrid = null;
		try {
			pangingParam = (PangingParam) ServletUtils.getParametersToBaseEntity(request, PangingParam.class);
			HashMap<String, Object> map = (HashMap) ServletUtils.getParametersToHashMap(request);
			dataGrid = new DataGrid();
			dataGrid.setPangingParam(pangingParam);
			map.put("startrow", dataGrid.getStartrow());
			map.put("endrow", dataGrid.getEndrow());
			map.put("rows", dataGrid.getRows());
			map.put("sort", dataGrid.getSort());
			map.put("order", dataGrid.getOrder());
			map.put("statusid", SysConstant.RecordStatus.VALID);
			if(map.containsKey("enddate")){
				Date tsDate=DataFormat.parseDate(map.get("enddate").toString(),DataFormat.DT_YYYY_MM_DD);
				map.put("enddate",DataFormat.formatDate(DataFormat.getNextDate(tsDate,5),DataFormat.DT_YYYY_MM_DD));
			}
			long resultCount = handAutoTaskService.queryAutoTaskResultCount(map);
			List<Autotask> resultList = handAutoTaskService.queryAutoTaskResultPage(map);
			DataStyle dataStyle = new DataStyle();
			dataStyle.setPageIndex(pangingParam.getPage());
			dataStyle.setDataCount(resultCount);
			dataStyle.setDataList(resultList);
			dataStyle.addDepict("id", DataTypeConstant.LONG);
			dataStyle.addDepict("code", DataTypeConstant.STRING);
			dataStyle.addDepict("name", DataTypeConstant.STRING);
			dataStyle.addDepict("executeclass", DataTypeConstant.STRING);
			dataStyle.addDepict("executemodel", DataTypeConstant.STRING);
			dataStyle.addDepict("description", DataTypeConstant.STRING);
			dataStyle.addDepict("servername", DataTypeConstant.STRING);
			dataStyle.addDepict("starttime", DataTypeConstant.DATETIME);
			dataStyle.addDepict("endtime", DataTypeConstant.DATETIME);
			dataStyle.addDepict("result", DataTypeConstant.STRING);
			dataStyle.addDepictByFunction("executestatus", SysConstant.ExecuteStatus.class, "getName", new Class[]{long.class});
			dataStyle.addDepictByFunction("taskstatus", SysConstant.TaskStatus.class, "getName", new Class[]{long.class});
			dataResult = PangingTools.buildResultPagerInfo(dataStyle);
			if (pangingParam.getReportExportType() == 0) {
				response.getWriter().write(JSONFactory.toJSONString(dataResult, userContext));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 启动新任务
	 * @param sysautotask
	 * @param scheduler
	 * @throws Exception
	 */
	private void startNewJob(Autotask sysautotask) throws Exception{
		// 初始化执行计划工厂
		SchedulerFactory schedulerFactory = new StdSchedulerFactory();
		// 从执行计划工厂得到一个调度计划
		Scheduler scheduler = schedulerFactory.getScheduler();
		//根据任务表的设置动态生成一个任务调度
		String jobcode = sysautotask.getCode()+"_RunOne";
		String jobgroup = "Job_RunOne_Group";
		String triggername = jobcode+"_cronTrigger";
		String triggergroup = "Trigger__RunOne_Group";
		
		//通过名字和组得到jobDectail
		JobDetail jobdetail=scheduler.getJobDetail(jobcode, jobgroup);
		//得到触发器
		SimpleTrigger simpleTrigger=(SimpleTrigger)scheduler.getTrigger(triggername, triggergroup);
		//如果自动任务已经在容器中运行
		if(jobdetail!=null&&simpleTrigger!=null)
		{
			scheduler.pauseTrigger(simpleTrigger.getName(), triggergroup);// 停止触发器   
			scheduler.unscheduleJob(simpleTrigger.getName(), triggergroup);// 移除触发器 
			//如果schedular是活动的
			scheduler.deleteJob(jobdetail.getName(),jobgroup);
		}
		//得到要执行的类名
		String executeClass = sysautotask.getExecuteclass();
		Class  sysautotasckClass = Class.forName(executeClass);
		// 产生一个jobdetail
		JobDetail jobDetail2 = new JobDetail(jobcode,jobgroup, sysautotasckClass);
		jobDetail2.getJobDataMap().put("AutotaskID", sysautotask.getId());
		//2、创建Trigger对象 
        SimpleTrigger strigger = new SimpleTrigger(); 
        strigger.setName(triggername); 
        strigger.setGroup(triggergroup); 
        strigger.setStartTime(new Date()); 
        //设置重复执行次数 
        strigger.setRepeatInterval(0);
        strigger.setRepeatCount(0);
		// 将job加入到执行计划中
		scheduler.scheduleJob(jobDetail2, strigger);
		//启动执行所有的计划中的jobdetail
		if(!scheduler.isStarted()){
			 scheduler.start();
		}
	}
}
